package com.huhao.springbootremotecallbyrabbitmq.controller;

import com.huhao.springbootremotecallbyrabbitmq.constants.RabbitMqConstants;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author huhao
 */
@RestController
public class MessageController {

    private final RabbitTemplate rabbitTemplate;

    public MessageController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @GetMapping("/send")
    public String sendMessage(@RequestParam("message") String message) {
        Message messageBo = new Message(message.getBytes(StandardCharsets.UTF_8));
        messageBo.getMessageProperties().setReplyTo(RabbitMqConstants.REPLY_QUEUE_NAME);
        messageBo.getMessageProperties().setCorrelationId(UUID.randomUUID().toString());
        // 直接发送字符串，RabbitTemplate会自动转换为Message对象
        Message message1 = rabbitTemplate.sendAndReceive(RabbitMqConstants.EXCHANGE_NAME, RabbitMqConstants.ROUTING_KEY, messageBo);
        if (message1 == null || message1.getBody() == null) {
            return null;
        }
        // 明确指定字符集，防止UnsupportedEncodingException
        System.err.println("收到回复：" + new String(message1.getBody(), StandardCharsets.UTF_8));
        return new String(message1.getBody(), StandardCharsets.UTF_8);
    }
}
